﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using Newtonsoft.Json;
using System.Drawing.Printing;

namespace MachineBuildingSystem
{
    public partial class OrderSendUC : UserControl
    {
        private string m_CurrentUser = "";
        private string m_Password = "";

        //操作权限
        private List<long> m_ActionList = new List<long>();
        private long m_SelectedProductLineId = -1;
        //当前销售订单
        private OrderInfo m_CurrentOrder = null;

        private DataTable m_BindDT = null;

        private DateTime m_SystemTime = DateTime.Now;

        //订单中仓位(即机楼系统中的物料名称)与物料id对照
        private Dictionary<string, long> m_SoreMaterialDic = new Dictionary<string, long>();

        //发货类型
        private int m_DeliveryWay = 3;
        public OrderSendUC()
        {
            InitializeComponent();
        }

        #region 初始化
        private void InitDT()
        {
            m_BindDT = new DataTable();
            m_BindDT.Columns.Add("deliId");
            //发货时间
            m_BindDT.Columns.Add("deliDate");
            //发货数量
            m_BindDT.Columns.Add("deliQuantity");
            //回收数量
            m_BindDT.Columns.Add("recoveredQuantity");
            //生产数量
            m_BindDT.Columns.Add("productQuantity");
            //生产线
            m_BindDT.Columns.Add("workingCenterName");
            //车牌号
            m_BindDT.Columns.Add("carCode");
            //司机
            m_BindDT.Columns.Add("driverName");
            //发货人
            m_BindDT.Columns.Add("makerName");
            //退砼状态
            m_BindDT.Columns.Add("returnStatus");
            //退砼数量
            m_BindDT.Columns.Add("returnQuantity");
            //备注
            m_BindDT.Columns.Add("remarks");
            //是否作废
            m_BindDT.Columns.Add("invalid");
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isDeliveryAdd">是否发货新增</param>
        /// <param name="order">订单信息</param>
        public void RefreshOrderSendInfo(string currentUser, string password, List<long> actionList, bool isDeliveryAdd, OrderInfo order)
        {
            try
            {
                InitDT();
                m_CurrentUser = currentUser;
                m_Password = password;
                m_ActionList = actionList;
                m_CurrentOrder = order;
                //填充订单信息
                FillOrderInfo(order);

                m_DeliveryWay = int.Parse(ConfigurationManager.AppSettings["DeliveryWay"]);

                BackgroundWorker backgroundWorker = new BackgroundWorker();
                backgroundWorker.DoWork +=backgroundWorker_DoWork;
                backgroundWorker.RunWorkerCompleted +=backgroundWorker_RunWorkerCompleted;
                backgroundWorker.RunWorkerAsync(order.id);
                //发货新增
                if (isDeliveryAdd)
                {
                    //显示关联客户销售金额
                    int belongcorpId = int.Parse(ConfigurationManager.AppSettings["BelongCorpId"]);
                    this.txtAccountAmount.Text = DataHelper.GetCusBalances(m_CurrentUser, m_Password,
                        belongcorpId, order.customerId, 1).ToString("0.00");
           
                    lcgFund.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    lcgSaleInfo.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    lcgDelivery.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    lcgBottom.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;

                    //根据订单Id获取当前订单的实施配方信息
                    m_SoreMaterialDic = new Dictionary<string, long>();
                    BackgroundWorker backgroundWorkerFormular = new BackgroundWorker();
                    backgroundWorkerFormular.DoWork += backgroundWorkerFormular_DoWork;
                    backgroundWorkerFormular.RunWorkerCompleted += backgroundWorkerFormular_RunWorkerCompleted;
                    backgroundWorkerFormular.RunWorkerAsync(m_CurrentOrder.id);
                }
                else
                {
                    lcgFund.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    lcgSaleInfo.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    lcgDelivery.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    lcgBottom.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("刷新发货信息明细异常：" + ex.ToString());
                MessageBox.Show(this, "加载发货界面异常：" + ex.Message);
            }
        }

        //填充订单信息
        private void FillOrderInfo(OrderInfo order)
        {
            try
            {
                txtCustomer.Text = order.customerName;
                txtOrderDate.Text = order.orderDate.ToString("yyyy-MM-dd");
                txtProjectName.Text = order.projectName;
                txtConstructionSite.Text = order.constructSite;
                txtFormulaCode.Text = order.materialCode;
                txtSstd.Text = order.materialSstd;
                txtSlump.Text = order.slump;
                txtActualRange.Text = order.actualRange.ToString();
                txtTransportation.Text = order.transport;
                txtPhone.Text = order.phone;
                txtOrderNumber.Text = order.orderQuantity.ToString("0.00");
                txtRemainedNumber.Text = (order.orderQuantity - order.sendQuantity).ToString("0.00");
                txtZone.Text = order.areaName;
            }
            catch (Exception ex)
            {
                LogHelper.error("填充订单信息异常：" + ex.ToString());
            }   
        }

        //生产消耗明显
        private void btnProductDetail_Click(object sender, EventArgs e)
        {
            ProductConsumeForm form = new ProductConsumeForm();
            form.OrderCode = m_CurrentOrder.orderCode;
            form.ShowDialog();
        }

        public delegate void sendReturnEventHandler(object sender, EventArgs e);
        public event sendReturnEventHandler sendReturnEvent;
        //返回
        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (sendReturnEvent != null)
                sendReturnEvent(null, null);
        }

        //发货新增时返回
        private void btnReturn_Click(object sender, EventArgs e)
        {
            if (sendReturnEvent != null)
                sendReturnEvent(null, null);
        }

        //退砼
        private void btnBackConcrete_Click(object sender, EventArgs e)
        {
            DataTable dt = this.gdcProduct.DataSource as DataTable;
            if (dt == null || dt.Rows.Count == 0)
            {
                MessageBox.Show("尚无发货单，无法进行退砼！");
                return;
            }
            BackConcreteForm form = new BackConcreteForm();
            form.CurrentUser = m_CurrentUser;
            form.Password = m_Password;
            form.ActionList = m_ActionList;
            form.DeliveryDT = dt;
            form.CurrentOrder = m_CurrentOrder;
            form.RefeshBackConcrete();
            form.ShowDialog();
            //关闭退砼界面后刷新列表
            BackgroundWorker backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += backgroundWorker_DoWork;
            backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
            backgroundWorker.RunWorkerAsync(m_CurrentOrder.id);
        }

        //费用登记
        private void btnRegistrationFee_Click(object sender, EventArgs e)
        {
            //DataTable dt = this.gdcProduct.DataSource as DataTable;
            //if (dt == null || dt.Rows.Count == 0)
            //{
            //    MessageBox.Show("尚无发货单，无法进行费用登记！");
            //    return;
            //}
            RegistrationFeeForm form = new RegistrationFeeForm();
            form.CurrentUser = m_CurrentUser;
            form.Password = m_Password;
            form.ActionList = m_ActionList;
            form.CurrentOrder = m_CurrentOrder;
            form.RefeshRegistrationFee();
            form.ShowDialog();
        }

        //发货
        private void btnSend_Click(object sender, EventArgs e)
        {
            DeliverySaveData deliverySaveData = this.deliveryOperationUC.GetDeliverySaveData();
            if (string.IsNullOrEmpty(deliverySaveData.carCode))
            {
                MessageBox.Show(this, "有发货单未输入车牌号，不能发货！");
                return;
            }
            if (deliverySaveData.workingId <= 0)
            {
                MessageBox.Show(this, "有发货单未选择生产线，不能发货！");
                return;
            }
            if ((deliverySaveData.productQuantity + deliverySaveData.recoveredQuantity) <= 0)
            {
                MessageBox.Show(this, "有发货单无发货数量，不能发货！");
                return;
            }
            //判断发货时间是否与默认时间一致
            if (deliverySaveData.deliDate != m_SystemTime)
            {
                if (DialogResult.Yes != MessageBox.Show(this, "发货时间与默认系统时间不一致，是否确定？", "",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                    return;
            }

            List<ProductDataInfo> productDataList = new List<ProductDataInfo>();

            string sql = "";
            if (m_DeliveryWay == 2 || m_DeliveryWay == 3)
            {
                sql = "select * from ProdMasterData where jobno = '"
                    + m_CurrentOrder.orderCode + "' and IsTransmit = 0 ";
                try
                {
                    DataTable dt = SqlServerHelper.CreateInstance().DoSqlSelect(sql);
                    if (dt.Rows.Count == 0 && (m_DeliveryWay == 2 || m_DeliveryWay == 3))
                    {
                        if (DialogResult.Yes != MessageBox.Show(this, "未获得生产数据，确认该订单是否为补录？"
                            + "若是,则选择生产数据，否则不能发货！", "",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                            return;
                        sql = "select * from ProdMasterData where IsTransmit = 0 and PDate >= '"
                            + deliverySaveData.deliDate.Date.ToString("yyyy-MM-dd HH:mm:ss") + "' and PDate <= '"
                            + deliverySaveData.deliDate.AddDays(1).Date.AddSeconds(-1).ToString("yyyy-MM-dd HH:mm:ss") + "'";
                        DataTable tempDT = SqlServerHelper.CreateInstance().DoSqlSelect(sql);
                        if (tempDT == null || tempDT.Rows.Count == 0)
                        {
                            MessageBox.Show(this, "生产系统中无生产数据，请确认!");
                            return;
                        }
                        ProMasterDataForm form = new ProMasterDataForm(tempDT);
                        if (form.ShowDialog() != DialogResult.OK)
                        {
                            MessageBox.Show(this, "尚未选择该车生产数据，不能发货！");
                            return;
                        }
                        productDataList = form.SelectedProductDataList;
                    }
                    if (dt.Rows.Count == 1)
                    {
                        ProductDataInfo data = new ProductDataInfo();
                        data.Prodno = long.Parse(dt.Rows[0]["ProdNo"].ToString());
                        data.Volume = decimal.Parse(dt.Rows[0]["Volume"].ToString());
                        data.pdate = Convert.ToDateTime(dt.Rows[0]["PDate"].ToString());
                        productDataList.Add(data);
                    }
                    if (dt.Rows.Count > 1)
                    {
                        ProMasterDataForm form = new ProMasterDataForm(dt);
                        if (form.ShowDialog() != DialogResult.OK)
                        {
                            MessageBox.Show(this, "尚未选择该车生产数据，不能发货！");
                            return;
                        }
                        productDataList = form.SelectedProductDataList;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.error("获取该车生产数据异常：" + ex.ToString());
                    MessageBox.Show(this, "获取该车生产数据异常：" + ex.ToString());
                    return;
                }
            }
            string tempJsonData = "";
            try
            {
                //保存发货单
                List<Dictionary<string, object>> list = GetDeliverySaveData(productDataList, deliverySaveData);
                if (list == null)
                    return;
                CGlobal.strSwapJsonData = JsonConvert.SerializeObject(list);
                tempJsonData = CGlobal.strSwapJsonData;
                LogHelper.info("订单：" + m_CurrentOrder.orderCode + "保存发货单JSon数据：" + tempJsonData);
                bool isSuccess = DataHelper.SaveSaleDelivery(m_CurrentUser, m_Password);

                if (isSuccess)
                {
                    try
                    {
                        if (m_DeliveryWay == 2 || m_DeliveryWay == 3)
                        {
                            string prodNoStr = "";
                            foreach (ProductDataInfo productDataInfo in productDataList)
                                prodNoStr += productDataInfo.Prodno.ToString() + ",";

                            sql = "update ProdMasterData set IsTransmit = 1 where ProdNo in (" + prodNoStr.TrimEnd(',') + ")";
                            isSuccess = SqlServerHelper.CreateInstance().DoSqlExecute(new string[] { sql });
                            if (!isSuccess)
                            {
                                MessageBox.Show(this, "消耗出库回填标识位保存失败！");
                                return;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.error("消耗出库回填标识位异常：" + ex.ToString() + "Sql:" + sql);
                        MessageBox.Show(this, "消耗出库回填标识位异常:" + ex.Message);
                        return;
                    }
                    MessageBox.Show(this, "发货成功！");
                }
                else
                {
                    LogHelper.error("发货传输Json数据：" + tempJsonData);
                    MessageBox.Show(this, "发货失败！");
                    return;
                }
                this.deliveryOperationUC.UpdateConfig(deliverySaveData.carCode, deliverySaveData.driverName);
                this.deliveryOperationUC.ClearForm();
                //保存成功后刷新发货单列表
                BackgroundWorker backgroundWorker = new BackgroundWorker();
                backgroundWorker.DoWork += backgroundWorker_DoWork;
                backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
                backgroundWorker.RunWorkerAsync(m_CurrentOrder.id);
            }
            catch (Exception ex)
            {
                LogHelper.error("发货保存信息异常：" + ex.ToString() + ",发货传输Json数据：" + tempJsonData);
                MessageBox.Show(this, "发货保存失败:" + ex.Message);
            }
        }

        private List<Dictionary<string, object>> GetDeliverySaveData(List<ProductDataInfo> productDataList, DeliverySaveData deliverySaveData)
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();

            decimal totalVolumn = 0;
            if (m_DeliveryWay == 2 || m_DeliveryWay == 3)
            {
                foreach (ProductDataInfo data in productDataList)
                {
                    if (deliverySaveData.deliDate.Date != data.pdate.Date)
                    {
                        MessageBox.Show(this, "发货时间:" + deliverySaveData.deliDate.ToString("yyyy-MM-dd")
                            + "与生产时间" + data.pdate.ToString("yyyy-MM-dd") + "不在一天，不能发货！");
                        return null;
                    }
                    totalVolumn += data.Volume;
                }
                //发货时若发货数量不等于生产数量则给出提示且不让保存
                if (deliverySaveData.productQuantity != totalVolumn)
                {
                    MessageBox.Show(this, "发货时输入生产数量：" + deliverySaveData.productQuantity
                        + "方不等于机楼生产数量：" + totalVolumn + " 方！");
                    return null;
                }
            }
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("orderId", m_CurrentOrder.id);
            dic.Add("carCode", deliverySaveData.carCode);
            dic.Add("driverName", deliverySaveData.driverName);
            dic.Add("workingId", deliverySaveData.workingId);
            dic.Add("productQuantity", deliverySaveData.productQuantity);
            dic.Add("recoveredQuantity", deliverySaveData.recoveredQuantity);
            dic.Add("mainQuantity", deliverySaveData.productQuantity + deliverySaveData.recoveredQuantity);
            dic.Add("deliDate", deliverySaveData.deliDate.ToString("yyyy-MM-dd HH:mm:ss"));
            if (m_DeliveryWay == 1 || m_DeliveryWay == 3)
                dic.Add("inMap", GetProductInStoreSaveData(deliverySaveData));
            if (m_DeliveryWay == 2 || m_DeliveryWay == 3)
                dic.Add("outMap", GetProductOutStoreSaveData(productDataList, deliverySaveData.deliDate.ToString("yyyy-MM-dd HH:mm:ss")));
            list.Add(dic);
            return list;
        }

        //生产入库JSon
        private List<Dictionary<string, object>> GetProductInStoreSaveData(DeliverySaveData deliverySaveData)
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();

            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("belongCorpId", int.Parse(ConfigurationManager.AppSettings["BelongCorpId"]));
            dic.Add("materialId", m_CurrentOrder.materialId);
            //入库数量是否为生产数量还是生产数量加上回收数量？
            dic.Add("mainQuantity", deliverySaveData.productQuantity);
            //添加销售订单Id
            dic.Add("saleLineId", m_CurrentOrder.id);
            //发货时间
            dic.Add("deliDate", deliverySaveData.deliDate.ToString("yyyy-MM-dd HH:mm:ss"));
            list.Add(dic);

            return list;
        }


        //消耗出库Json
        private List<Dictionary<string, object>> GetProductOutStoreSaveData(List<ProductDataInfo> productDataList, string deliDateStr)
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();

            string prodNoStr = "";
            foreach (ProductDataInfo productDataInfo in productDataList)
                prodNoStr += productDataInfo.Prodno.ToString() + ",";

            bool isChange = int.Parse(ConfigurationManager.AppSettings["IsChange"]) == 1 ? true : false;
            string sql = "select * from ConsumpMaterial where ProdNo in (" + prodNoStr.TrimEnd(',') + ")";
            try
            {
                DataTable dt = SqlServerHelper.CreateInstance().DoSqlSelect(sql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        dic.Add("belongCorpId", int.Parse(ConfigurationManager.AppSettings["BelongCorpId"]));
                        string materialName = dr["MaterialName"].ToString();
                        if (m_SoreMaterialDic.ContainsKey(materialName))
                            dic.Add("materialId", m_SoreMaterialDic[materialName]);
                        else
                        {
                            dic.Add("materialId", -1);
                            LogHelper.info("消耗出库时根据物料名称:" + materialName + "未匹配对应的物料Id");
                        }
                        //机楼系统单位为KG，存到系统中为吨,若配置文件动库存，则mainQuantity为实际消耗，若不动库存，则为0
                        decimal act = decimal.Parse(dr["MAct"].ToString()) / 1000;

                        dic.Add("mainQuantity", isChange == true ? act : 0);
                        dic.Add("realQuantity", act);

                        //添加销售id 
                        dic.Add("saleLineId", m_CurrentOrder.id);
                        //发货时间
                        dic.Add("deliDate", deliDateStr);
                        list.Add(dic);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("获取生产消耗异常：" + ex.Message);
            }

            bool isHand = int.Parse(ConfigurationManager.AppSettings["IsHand"]) == 1 ? true : false;

            if (isHand)
            {
                string handSql = "select * from HandBatchInfo where ProdNo in (" + prodNoStr.TrimEnd(',') + ")";
                try
                {
                    DataTable handDT = SqlServerHelper.CreateInstance().DoSqlSelect(handSql);

                    if (handDT != null && handDT.Rows.Count > 0)
                    {
                        foreach (DataRow dr in handDT.Rows)
                        {
                            Dictionary<string, object> dic = new Dictionary<string, object>();
                            dic.Add("belongCorpId", int.Parse(ConfigurationManager.AppSettings["BelongCorpId"]));
                            string materialName = dr["MaterialName"].ToString();
                            if (m_SoreMaterialDic.ContainsKey(materialName))
                                dic.Add("materialId", m_SoreMaterialDic[materialName]);
                            else
                            {
                                dic.Add("materialId", -1);
                                LogHelper.info("消耗出库时根据物料名称:" + materialName + "未匹配对应的物料Id");
                            }
                            //机楼系统单位为KG，存到系统中为吨,若配置文件动库存，则mainQuantity为实际消耗，若不动库存，则为0
                            decimal count = decimal.Parse(dr["OpCount"].ToString()) / 1000;
                            dic.Add("mainQuantity", isChange == true ? count : 0);
                            dic.Add("realQuantity", count);

                            //添加销售id 
                            dic.Add("saleLineId", m_CurrentOrder.id);
                            //发货时间
                            dic.Add("deliDate", deliDateStr);
                            list.Add(dic);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.error("获取手动生产消耗异常：" + ex.Message);
                }
            }
            return list;
        }

        //验证客户资金
        private void btnValidate_Click(object sender, EventArgs e)
        {

        }

        //红冲
        private void btnRed_Click(object sender, EventArgs e)
        {
            if (!m_ActionList.Contains((int)ActionEnum.Red))
            {
                MessageBox.Show(this, "该用户无红冲权限！");
                return;
            }
            DataRow currentRow = this.gdvProduct.GetFocusedDataRow();
            if (currentRow == null)
            {
                MessageBox.Show(this, "请先选择需要红冲的发货单!");
                return;
            }
            if (DialogResult.Yes != MessageBox.Show(this, "是否确认红冲该条发货单？", "",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                return;
            long deliId = Convert.ToInt64(currentRow["deliId"]);
            try
            {
                if (!DataHelper.SaveBackSale(m_CurrentUser, m_Password, deliId))
                    return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "发货单红冲失败：" + ex.Message);
                return;
            }
            
            MessageBox.Show(this, "发货单红冲成功！");
            //红冲结束后刷新列表
            BackgroundWorker backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += backgroundWorker_DoWork;
            backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
            backgroundWorker.RunWorkerAsync(m_CurrentOrder.id);
        }

        #region 发货明细后台操作
        private List<DeliveryInfo> m_DeliveryInfoList = new List<DeliveryInfo>();
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            long orderId = Convert.ToInt64(e.Argument);
            try
            {
                m_DeliveryInfoList = DataHelper.GetSaleDeliverys(m_CurrentUser, m_Password, orderId);
            }
            catch(Exception ex)
            {
                throw new Exception("根据订单ID：" + orderId + "获取发货单详情异常：" + ex.Message);
            }
            e.Result = m_DeliveryInfoList;
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
                return;
            if (e.Error != null)
            {
                LogHelper.error(e.Error.Message);
                MessageBox.Show(e.Error.Message);
                return;
            }
            m_BindDT.Clear();
            this.gdcProduct.DataSource = m_BindDT;
            List<DeliveryInfo> deliveryInfoList = e.Result as List<DeliveryInfo>;
            if (deliveryInfoList == null || deliveryInfoList.Count == 0)
                return;
            //按发货时间降序排序
            List<DeliveryInfo>  tempList = deliveryInfoList.OrderByDescending(temp => temp.deliDate).ToList<DeliveryInfo>();
            BindData(tempList);
        }

        //绑定列表
        private void BindData(List<DeliveryInfo> deliveryInfoList)
        {
            try
            {
                string returnStatus = "";
                foreach (DeliveryInfo deliveryInfo in deliveryInfoList)
                {
                    switch (deliveryInfo.returnStatus)
                    {
                        case (int)ReturnStatusEnum.ALLSIGNS_WASTE:
                            returnStatus = "全部签收，废料处理";
                            break;
                        case (int)ReturnStatusEnum.ALLSIGNS_SELF:
                            returnStatus = "全部签收，直接发往本客户其他工地";
                            break;
                        case (int)ReturnStatusEnum.ALLSIGNS_OTHER:
                            returnStatus = "全部签收，调料后发往其他工地";
                            break;
                        case (int)ReturnStatusEnum.PARTSIGNS_WASTE:
                            returnStatus = "部分签收，废料处理";
                            break;
                        case (int)ReturnStatusEnum.PARTSIGNS_SELF:
                            returnStatus = "部分签收，直接发往本客户其他工地";
                            break;
                        case (int)ReturnStatusEnum.PARTSIGNS_OTHER:
                            returnStatus = "部分签收，调料后发往其他工地";
                            break;
                        case (int)ReturnStatusEnum.ALLOCATE_SELF:
                            returnStatus = "调拨发货，发往本客户其他工地";
                            break;
                        case (int)ReturnStatusEnum.RETURN_OTHER:
                            returnStatus = "剩余发货，发往其他工地";
                            break;
                        case (int)ReturnStatusEnum.PART_BACK:
                            returnStatus = "部分退货";
                            break;
                        default:
                            returnStatus = "";
                            break;
                    }
                    m_BindDT.Rows.Add(deliveryInfo.id, deliveryInfo.deliDate, deliveryInfo.deliQuantity,
                        deliveryInfo.recoveredQuantity, deliveryInfo.productQuantity, deliveryInfo.workingCenterName,
                        deliveryInfo.carCode, deliveryInfo.driverName, deliveryInfo.makerName, 
                        returnStatus, deliveryInfo.returnQuantity, deliveryInfo.remarks,
                        deliveryInfo.invalid == true ? "是" : "否");
                }
                this.gdcProduct.DataSource = m_BindDT;
            }
            catch (Exception ex)
            {
                LogHelper.error("绑定发货单列表异常：" + ex.ToString());
                MessageBox.Show("绑定发货单列表异常:" + ex.Message);
            }
        }
        #endregion

        private void OrderSendUC_Load(object sender, EventArgs e)
        {
            ContextMenu emptyMenu = new ContextMenu();
            txtCustomer.Properties.ContextMenu = emptyMenu;
            txtOrderDate.Properties.ContextMenu = emptyMenu;
            txtProjectName.Properties.ContextMenu = emptyMenu;
            txtConstructionSite.Properties.ContextMenu = emptyMenu;
            txtFormulaCode.Properties.ContextMenu = emptyMenu;
            txtSstd.Properties.ContextMenu = emptyMenu;
            txtSlump.Properties.ContextMenu = emptyMenu;
            txtActualRange.Properties.ContextMenu = emptyMenu;
            txtTransportation.Properties.ContextMenu = emptyMenu;
            txtPhone.Properties.ContextMenu = emptyMenu;
            txtOrderNumber.Properties.ContextMenu = emptyMenu;
            txtRemainedNumber.Properties.ContextMenu = emptyMenu;
            txtZone.Properties.ContextMenu = emptyMenu;
            txtAccountAmount.Properties.ContextMenu = emptyMenu;
        }

        private void gdvProduct_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        #region 线程
        private void backgroundWorkerFormular_DoWork(object sender, DoWorkEventArgs e)
        {
            long orderId = long.Parse(e.Argument.ToString());
            List<SaleFormulasData> saleFormulasDataList = null;
            try
            {
                saleFormulasDataList = DataHelper.GetSaleFormulas(m_CurrentUser, m_Password, orderId);
                if (saleFormulasDataList != null && saleFormulasDataList.Count >= 0)
                {
                    foreach (SaleFormulasData data in saleFormulasDataList)
                    {
                        List<SaConcreteFormulaData> subList = DataHelper.GetSaConcreteFormulaLines(m_CurrentUser, m_Password, data.id);
                        if (subList != null)
                            data.SaConcreteFormulaDataList = subList;
                    }
                }
            }
            catch
            {
                throw;
            }
            e.Result = saleFormulasDataList;
        }

        private void backgroundWorkerFormular_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
                return;
            if (e.Error != null)
            {
                LogHelper.error("加载实施配方数据异常：" + e.Error.Message);
                return;
            }
            List<SaleFormulasData> saleFormulasDataList = e.Result as List<SaleFormulasData>;
            if (saleFormulasDataList == null || saleFormulasDataList.Count == 0)
                return;
            try
            {
                foreach (SaleFormulasData saleFormulasData in saleFormulasDataList)
                {
                    foreach (SaConcreteFormulaData saConcreteFormulaData in saleFormulasData.SaConcreteFormulaDataList)
                    {
                        if (!m_SoreMaterialDic.ContainsKey(saConcreteFormulaData.controlStoreName))
                            m_SoreMaterialDic.Add(saConcreteFormulaData.controlStoreName, saConcreteFormulaData.materialId);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("加载仓位与物料对照异常：" + ex.Message);
                MessageBox.Show(this, "加载仓位与物料对照异常：" + ex.Message);
            }
           
            try
            {
                m_SystemTime = DataHelper.GetSystemTime(m_CurrentUser, m_Password);
                this.deliveryOperationUC.FillInfo(m_CurrentOrder, m_SystemTime);
            }
            catch (Exception ex)
            {
                LogHelper.error("填充订单信息异常：" + ex.Message);
                MessageBox.Show(this,"填充订单信息异常：" + ex.Message);
            }
        }
        #endregion

        //打印发货单
        private DeliveryInfo m_DeliveryInfoPrint = new DeliveryInfo();
        private void btnPrint_Click(object sender, EventArgs e)
        {
            DataRow currentRow = this.gdvProduct.GetFocusedDataRow();
            if (currentRow == null)
            {
                MessageBox.Show(this, "请选择需要打印的发货单！");
                return;
            }
            long deliId = long.Parse(currentRow["deliId"].ToString());
            var query = from temp in m_DeliveryInfoList
                        where temp.id == deliId
                        select temp;
            if (query == null || query.Count() == 0)
                return;
             m_DeliveryInfoPrint = query.ToList<DeliveryInfo>()[0];

             if (!DoPrintHandler())
             {
                 MessageBox.Show(this, "打印失败！");
                 return;
             }
             MessageBox.Show(this, "打印成功！");
        }

        private PrintDocument m_PrintDocument;
        private bool DoPrintHandler()
        {
            m_PrintDocument = new PrintDocument();
            m_PrintDocument.PrintPage += m_PrintDocument_PrintPage;
            try
            {
                m_PrintDocument.Print();
            }
            catch (Exception ex)
            {
                LogHelper.error("打印错误：" + ex.Message);
                return false;
            }
            return true;
        }

        void m_PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            Font font = new Font("宋体", 12);
            Brush brush = Brushes.Blue;
            decimal distanceX = decimal.Parse(ConfigurationManager.AppSettings["DistanceX"].ToString());
            decimal distanceY = decimal.Parse(ConfigurationManager.AppSettings["DistanceY"].ToString());
            try
            {
                //送货日期
                e.Graphics.DrawString(m_DeliveryInfoPrint.deliDate.ToString("yyyy-MM-dd"), font, brush, (float)(100 + distanceX), (float)(100 + distanceY));
                //客户名称
                e.Graphics.DrawString(m_CurrentOrder.customerName, font, brush, (float)(100 + distanceX), (float)(150 + distanceY));
                //联系人
                e.Graphics.DrawString(m_CurrentOrder.phone, font, brush, (float)(500 + distanceX), (float)(150 + distanceY));
                //施工地址
                e.Graphics.DrawString(m_CurrentOrder.constructionAddr, font, brush, (float)(100 + distanceX), (float)(200 + distanceY));
                //强度等级
                e.Graphics.DrawString(m_CurrentOrder.strengthGrade, font, brush, (float)(500 + distanceX), (float)(200 + distanceY));
                //工程名称
                e.Graphics.DrawString(m_CurrentOrder.projectName, font, brush, (float)(100 + distanceX), (float)(250 + distanceY));
                //卸料方式
                e.Graphics.DrawString(m_CurrentOrder.transport, font, brush, (float)(500 + distanceX), (float)(250 + distanceY));
                //工程部位
                e.Graphics.DrawString(m_CurrentOrder.constructSite, font, brush, (float)(100 + distanceX), (float)(300 + distanceY));
                //坍落度
                e.Graphics.DrawString(m_CurrentOrder.slump, font, brush, (float)(500 + distanceX), (float)(300 + distanceY));
                //本车次方量
                e.Graphics.DrawString(m_DeliveryInfoPrint.deliQuantity.ToString(), font, brush, (float)(100 + distanceX), (float)(350 + distanceY));
                //生产线编号
                e.Graphics.DrawString(m_CurrentOrder.workingCenterName, font, brush, (float)(100 + distanceX), (float)(400 + distanceY));
                //运输车号
                e.Graphics.DrawString(m_DeliveryInfoPrint.carCode, font, brush, (float)(300 + distanceX), (float)(400 + distanceY));
                //发货时间
                e.Graphics.DrawString(m_DeliveryInfoPrint.deliDate.ToString("HH:mm:ss"), font, brush, (float)(100 + distanceX), (float)(450 + distanceY));
                //操作员
                e.Graphics.DrawString(m_DeliveryInfoPrint.makerName, font, brush, (float)(100 + distanceX), (float)(550 + distanceY));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!m_ActionList.Contains((int)ActionEnum.DeliModify))
            {
                MessageBox.Show(this, "该用户无修改发货单权限！");
                return;
            }
            DataRow currentRow = this.gdvProduct.GetFocusedDataRow();
            if (currentRow == null)
            {
                MessageBox.Show(this, "请选择需要修改的发货单！");
                return;
            }
            long deliId = long.Parse(currentRow["deliId"].ToString());

            string carCode = currentRow["carCode"].ToString();
            string driverName = currentRow["driverName"].ToString();
            DeliveryModifyForm form = new DeliveryModifyForm();
            form.CarCode = carCode;
            form.Driver = driverName;
            if (form.ShowDialog() == DialogResult.OK)
            {
                string newCarCode = form.CarCode;
                string newDriver = form.Driver;
                try
                {
                    Dictionary<string, object> dic = GetDeliverySaveUpdateData(deliId, newCarCode, newDriver);
                    CGlobal.strSwapJsonData = JsonConvert.SerializeObject(dic);
                    if (!DataHelper.ChangeDelivery(m_CurrentUser, m_Password))
                        return;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "发货单修改失败：" + ex.Message);
                    return;
                }

                MessageBox.Show(this, "发货单修改成功！");
                //红冲结束后刷新列表
                BackgroundWorker backgroundWorker = new BackgroundWorker();
                backgroundWorker.DoWork += backgroundWorker_DoWork;
                backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
                backgroundWorker.RunWorkerAsync(m_CurrentOrder.id);
            }
        }

        private Dictionary<string, object> GetDeliverySaveUpdateData(long deliveryId, string carCode, string driverName)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("deliveryId", deliveryId);
            dic.Add("carCode", carCode);
            dic.Add("driverName", driverName);
            return dic;
        }
    }
}
